package sword_offer;

/**
 * @author Synhard
 * @version 1.0
 * @Class sword_offer.Code3
 * @Description 打印回型矩阵
 * @tel 13001321080
 * @email 823436512@qq.com
 * @date 2021-03-08 17:06
 */
public class Code3 {
    public static void main(String[] args) {
        generateMatrix(4);
    }

    public static int[][] generateMatrix(int n) {
        int top = 0, left = 0, bottom = n - 1, right = n - 1;
        int[][] res = new int[n][n];
        int counter = 1;
        while (true) {
            for (int i = left; i <= right; i++) {
                res[top][i] = counter++; // 从左向右赋值
            }
            if (++top > bottom) {
                break;
            }
            for (int i = top; i <= bottom; i++) {
                res[i][right] = counter++; // 从上向下赋值
            }
            if (--right < left) {
                break;
            }
            for (int i = right; i >= left; i--) {
                res[bottom][i] = counter++; // 从右向左赋值
            }
            if (--bottom < top) {
                break;
            }
            for (int i = bottom; i >= top; i--) {
                res[i][left] = counter++; // 从下向上赋值
            }
            if (++left > right) {
                break;
            }
        }
        return res;
    }

}
